﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using System.Web.UI.WebControls;
using AgileShare.Framework.Core;

namespace AgileShare.Framework.Library.Helpers
{
	/// <summary>
	/// This class contains helper methods for working with the User Interface
	/// - All methods should be static
	/// - DO NOT USE SPContext
	/// </summary>
	public static class UIHelper
	{
		/// <summary>
		/// Find Control recursively.
		/// </summary>
		/// <param name="root"></param>
		/// <param name="id"></param>
		/// <returns></returns>
		public static Control FindControlRecursive(Control root, string id)
		{
			if (root.ID == id)
			{
				return root;
			}

			foreach (Control c in root.Controls)
			{
				Control t = FindControlRecursive(c, id);
				if (t != null)
				{
					return t;
				}
			}

			return null;
		}

        /// <summary>
        /// Logs an error in the ULS log and inserts a literal control with a message.
        /// Useful when an error occurs in a webpart, to encapsulate the error and display a notification message (instead of breaking the page)
        /// </summary>
        /// <param name="displayMessage">The message to display to the user. Will be inserted in a Literal control.</param>
        /// <param name="logMessage">The message to Log to ULS.</param>
        /// <param name="controls">The Controls collection where the Literal control will be inserted.</param>
        /// <param name="exception">The exception that occurred.</param>
        public static void LogErrorAndShowErrorMessage(string displayMessage, string logMessage, ControlCollection controls, Exception exception)
        {
            TraceProvider.Log(displayMessage, TraceProviderCategories.Default, (uint)TraceProviderEventIds.WebParts, TraceProviderSeverity.Error);

            LiteralControl literal = new LiteralControl(displayMessage);
            controls.Add(literal);
        }


        /// <summary>
        /// Disable validation controls on a page while the page is in edit mode.
        /// </summary>
        /// <param name="validationGroupName"></param>
        /// <param name="page"></param>
        public static void DisableValidatorsInEditMode(string validationGroupName, Page page)
        {
            if (SPContext.Current.FormContext.FormMode != SPControlMode.Display)
            {
                // disable all validation
                foreach (BaseValidator validator in page.GetValidators(validationGroupName))
                {
                    validator.Enabled = false;
                }
            }
        }
	}
}
